package com.pinc.poop;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;

public class validate extends WidgetActivity implements AdListener{
	private EditText et_pwd1;
	private EditText et_pwd2;
	private EditText et_pwd3;
	private EditText et_pwd4;
	private TextView tv_wrong;
	private AdView adview;
	private SharedPreferences settings;

	public static final String VALID_FILE_NAME = "validxxx";
	public static final int val_timeout = 2000;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.validate);
		initWidget();
	}

	@Override
	protected void onPostResume() {
		super.onPostResume();
		loadAD();
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					Thread.sleep(400, 0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				validate.this.runOnUiThread(new Runnable(){
					@Override
					public void run() {
						InputMethodManager imm = (InputMethodManager)validate.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
						imm.showSoftInput(et_pwd1, 0);
						imm.showSoftInput(et_pwd2, 0);
						imm.showSoftInput(et_pwd3, 0);
						imm.showSoftInput(et_pwd4, 0);
					}
				});
			}
		}).start();

		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					Thread.sleep(1600, 0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				validate.this.runOnUiThread(new Runnable(){
					@Override
					public void run() {
						InputMethodManager imm = (InputMethodManager)validate.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
						imm.showSoftInput(et_pwd1, 0);
						imm.showSoftInput(et_pwd2, 0);
						imm.showSoftInput(et_pwd3, 0);
						imm.showSoftInput(et_pwd4, 0);
					}
				});
			}
		}).start();
	}

	@Override
	protected void initWidget() {
		/* adview */
		adview = (AdView) this.findViewById(R.id.adView);
		adview.setAdListener(this);

		et_pwd1 = (EditText) this.findViewById(R.id.editText1);
		et_pwd2 = (EditText) this.findViewById(R.id.editText2);
		et_pwd3 = (EditText) this.findViewById(R.id.editText3);
		et_pwd4 = (EditText) this.findViewById(R.id.editText4);
		tv_wrong = (TextView) this.findViewById(R.id.textView2);

		/* set upbar */
		TextView bt_prev = (TextView) this.findViewById(R.id.button_left);
		bt_prev.setVisibility(View.GONE);
		TextView bt_next = (TextView) this.findViewById(R.id.button_right);
		bt_next.setVisibility(View.GONE);
		TextView tv_title = (TextView) findViewById(R.id.textView_title);
		tv_title.setText(getResources().getString(R.string.app_name));

		et_pwd1.addTextChangedListener(new pwdListener(et_pwd2));
		et_pwd2.addTextChangedListener(new pwdListener(et_pwd3));
		et_pwd3.addTextChangedListener(new pwdListener(et_pwd4));
		et_pwd4.addTextChangedListener(new pwdLastListner());

		et_pwd1.setOnFocusChangeListener(new pwdFocusListener()); 
		et_pwd2.setOnFocusChangeListener(new pwdFocusListener());
		et_pwd3.setOnFocusChangeListener(new pwdFocusListener());

		et_pwd2.setOnKeyListener(new pwdDelListener(et_pwd1));
		et_pwd3.setOnKeyListener(new pwdDelListener(et_pwd2));
		et_pwd4.setOnKeyListener(new pwdDelListener(et_pwd3));
	}

	private class pwdDelListener implements View.OnKeyListener
	{
		private EditText edt_prev;

		public pwdDelListener(EditText edt_prev) {
			this.edt_prev = edt_prev;
		}

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if ( event.getAction() == KeyEvent.ACTION_DOWN  && keyCode == KeyEvent.KEYCODE_DEL)
			{
				if ( ((EditText)v).getText().length() == 0)
				{
					edt_prev.requestFocus();
				}
			}
			return false;
		}
	}

	private class pwdFocusListener implements View.OnFocusChangeListener
	{
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if ( hasFocus)
				((EditText)v).setText("");
		}
	}

	private class pwdLastListner implements TextWatcher
	{
		private boolean res;
		private CharSequence last;
		@Override
		public void afterTextChanged(Editable s) {
			if (res)
			{
				et_pwd4.setText("");
				if (isPass(String.format("%s%s%s%s", et_pwd1.getText(), et_pwd2.getText(), et_pwd3.getText(), last), validate.this))
				{
					createPass(validate.this.getCacheDir());
					validate.this.finish();
				}
				else
				{
					loadAD();
					tv_wrong.setVisibility(View.VISIBLE);
					et_pwd2.setText("");
					et_pwd3.setText("");
					et_pwd4.setText("");
					et_pwd1.requestFocus();
				}
			}
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,	int after) {}
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			res = (s.length() == 1)?true:false;
			last = (s.length() == 1)?s:last;
		}
	}

	private class pwdListener implements TextWatcher
	{
		private boolean res;
		private EditText et_next;

		public pwdListener(EditText et_next) {
			res = false;
			this.et_next = et_next;
		}

		@Override
		public void afterTextChanged(Editable s) {
			if (res)
			{
				et_next.requestFocus();
				tv_wrong.setVisibility(View.INVISIBLE);
			}	
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,	int after) {
		}
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			res = (s.length() == 1)?true:false;
		}
	}

	private static boolean isPass(String iPwd, Context ctx)
	{
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx);
		if ( iPwd.compareTo(settings.getString("password", "12345")) == 0)
		{
			return true;
		}
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ( keyCode == KeyEvent.KEYCODE_BACK)
		{
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public static void createPass(File file)
	{
		File val_file = new File(file, VALID_FILE_NAME);
		Time now = new Time();
		now.setToNow();

		try {
			val_file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if ( val_file.exists())
		{
			val_file.setLastModified(now.toMillis(true));
		}
	}

	private void loadAD()
	{
		adview.setVisibility(View.GONE);
		AdRequest request = new AdRequest();
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		String user_sex_str = settings.getString("user_sex", "null");
		if ( user_sex_str.compareTo(getResources().getStringArray(R.array.str_arr_gender)[0]) == 0)
		{
			request.setGender(AdRequest.Gender.FEMALE);
		}
		else if( user_sex_str.compareTo(getResources().getStringArray(R.array.str_arr_gender)[1]) == 0)
		{
			request.setGender(AdRequest.Gender.MALE);
		}

		adview.loadAd(request);
	}

	@Override
	public void onDismissScreen(Ad arg0) {
	}

	@Override
	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
	}

	@Override
	public void onLeaveApplication(Ad arg0) {
	}

	@Override
	public void onPresentScreen(Ad arg0) {
	}

	@Override
	public void onReceiveAd(Ad arg0) {
		adview.setVisibility(View.VISIBLE);
	}

}
